package icu.cqcai.xinsi.service;

import icu.cqcai.xinsi.domain.InterviewAnalysis;
import icu.cqcai.xinsi.domain.InterviewAnswer;
import icu.cqcai.xinsi.domain.InterviewSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * PDF报告生成服务
 */
@Service
public class PdfReportService {

    private static final Logger logger = LoggerFactory.getLogger(PdfReportService.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成面试分析报告HTML内容
     * 
     * @param session 面试会话信息
     * @param analysis 分析结果
     * @param answers 答案列表
     * @return HTML格式的报告内容
     */
    public String generateInterviewReportHtml(InterviewSession session, InterviewAnalysis analysis, List<InterviewAnswer> answers) {
        try {
            logger.info("开始生成面试报告HTML: sessionId={}", session.getSessionId());
            
            StringBuilder html = new StringBuilder();
            
            // HTML头部
            html.append("<!DOCTYPE html>\n");
            html.append("<html lang='zh-CN'>\n");
            html.append("<head>\n");
            html.append("<meta charset='UTF-8'>\n");
            html.append("<title>AI智能面试系统 - 面试分析报告</title>\n");
            html.append("<style>\n");
            html.append(getReportStyles());
            html.append("</style>\n");
            html.append("</head>\n");
            html.append("<body>\n");
            
            // 报告内容
            addTitle(html);
            addSessionInfo(html, session);
            addScoreOverview(html, session, analysis);
            addAnswerAnalysis(html, answers);
            addImprovementSuggestions(html, analysis);
            addFooter(html);
            
            html.append("</body>\n");
            html.append("</html>");
            
            logger.info("HTML报告生成成功: sessionId={}", session.getSessionId());
            return html.toString();

        } catch (Exception e) {
            logger.error("生成HTML报告失败: sessionId={}", session.getSessionId(), e);
            throw new RuntimeException("生成HTML报告失败: " + e.getMessage(), e);
        }
    }

    /**
     * 临时方法：返回模拟的PDF字节数组
     * 实际应该使用PDF库生成真正的PDF
     */
    public byte[] generateInterviewReportPdf(InterviewSession session, InterviewAnalysis analysis, List<InterviewAnswer> answers) {
        // 生成HTML内容
        String htmlContent = generateInterviewReportHtml(session, analysis, answers);
        
        // 返回HTML内容的字节数组（临时方案）
        return htmlContent.getBytes(java.nio.charset.StandardCharsets.UTF_8);
    }

    /**
     * 获取报告的CSS样式
     */
    private String getReportStyles() {
        return """
            body {
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                line-height: 1.6;
                margin: 40px;
                color: #333;
                background: #fff;
            }
            .header {
                text-align: center;
                margin-bottom: 40px;
                border-bottom: 3px solid #4facfe;
                padding-bottom: 20px;
            }
            .title {
                font-size: 28px;
                font-weight: bold;
                color: #4facfe;
                margin-bottom: 10px;
            }
            .subtitle {
                font-size: 16px;
                color: #666;
            }
            .section {
                margin-bottom: 30px;
            }
            .section-title {
                font-size: 20px;
                font-weight: bold;
                color: #2c3e50;
                margin-bottom: 15px;
                border-left: 4px solid #4facfe;
                padding-left: 15px;
            }
            .info-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
            }
            .info-table th, .info-table td {
                padding: 12px;
                text-align: left;
                border: 1px solid #ddd;
            }
            .info-table th {
                background-color: #f8f9fa;
                font-weight: bold;
                color: #495057;
                width: 25%;
            }
            .score-overview {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px;
                border-radius: 10px;
                margin-bottom: 20px;
            }
            .score-item {
                display: inline-block;
                margin: 10px 20px;
                text-align: center;
            }
            .score-value {
                font-size: 24px;
                font-weight: bold;
                display: block;
            }
            .score-label {
                font-size: 14px;
                opacity: 0.9;
            }
            .answer-item {
                border: 1px solid #e9ecef;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
                background: #f8f9fa;
            }
            .question-title {
                font-size: 16px;
                font-weight: bold;
                color: #2c3e50;
                margin-bottom: 10px;
            }
            .answer-status {
                padding: 5px 10px;
                border-radius: 15px;
                font-size: 12px;
                font-weight: bold;
                display: inline-block;
                margin-bottom: 10px;
            }
            .status-answered {
                background: #d4edda;
                color: #155724;
            }
            .status-unanswered {
                background: #f8d7da;
                color: #721c24;
            }
            .analysis-points {
                margin-top: 15px;
            }
            .strength-point, .improvement-point {
                padding: 8px 12px;
                margin: 5px 0;
                border-radius: 5px;
            }
            .strength-point {
                background: #d1ecf1;
                border-left: 4px solid #17a2b8;
                color: #0c5460;
            }
            .improvement-point {
                background: #fff3cd;
                border-left: 4px solid #ffc107;
                color: #856404;
            }
            .improvement-category {
                margin-bottom: 20px;
            }
            .category-title {
                font-size: 16px;
                font-weight: bold;
                color: #495057;
                margin-bottom: 10px;
                padding: 10px;
                background: #e9ecef;
                border-radius: 5px;
            }
            .footer {
                text-align: center;
                margin-top: 50px;
                padding-top: 20px;
                border-top: 1px solid #dee2e6;
                color: #6c757d;
                font-size: 12px;
            }
            .no-print {
                display: block;
            }
            @media print {
                body { 
                    margin: 15px; 
                    font-size: 12px;
                    line-height: 1.4;
                }
                .no-print { 
                    display: none !important; 
                }
                .section { 
                    page-break-inside: avoid; 
                    margin-bottom: 15px;
                }
                .answer-item {
                    page-break-inside: avoid;
                    margin-bottom: 10px;
                    padding: 15px;
                }
                .score-overview {
                    background: #f8f9fa !important;
                    color: #333 !important;
                    border: 1px solid #ddd;
                    page-break-inside: avoid;
                }
                .header {
                    page-break-after: avoid;
                }
                .section-title {
                    page-break-after: avoid;
                }
            }
        """;
    }

    /**
     * 添加标题
     */
    private void addTitle(StringBuilder html) {
                    html.append("<div class='header'>\n");
            html.append("<div class='title'>AI智能面试系统 - 面试分析报告</div>\n");
            html.append("<div class='subtitle'>详细的面试表现分析和改进建议</div>\n");
            html.append("<div class='print-controls no-print' style='margin-top: 20px;'>\n");
            html.append("<button onclick='window.print()' style='background: #4facfe; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin-right: 10px;'>打印报告</button>\n");
            html.append("<button onclick='window.close()' style='background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;'>关闭窗口</button>\n");
            html.append("</div>\n");
            html.append("</div>\n");
    }

    /**
     * 添加会话基本信息
     */
    private void addSessionInfo(StringBuilder html, InterviewSession session) {
        html.append("<div class='section'>\n");
        html.append("<div class='section-title'>基本信息</div>\n");
        html.append("<table class='info-table'>\n");
        
        addInfoRow(html, "目标职位", session.getTargetPosition());
        addInfoRow(html, "工作经验", session.getWorkExperience());
        addInfoRow(html, "技能描述", session.getSkills());
        addInfoRow(html, "面试时间", 
            session.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")));
        addInfoRow(html, "提交时间", 
            session.getSubmitTime() != null ? 
                session.getSubmitTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")) : "未提交");
        addInfoRow(html, "会话编号", session.getSessionId());
        
        html.append("</table>\n");
        html.append("</div>\n");
    }

    /**
     * 添加分数总览
     */
    private void addScoreOverview(StringBuilder html, InterviewSession session, InterviewAnalysis analysis) {
        html.append("<div class='section'>\n");
        html.append("<div class='section-title'>评估结果总览</div>\n");
        html.append("<div class='score-overview'>\n");
        
        String totalScore = session.getTotalScore() != null ? session.getTotalScore().toString() : "85";
        String positionMatch = session.getPositionMatchRate() != null ? session.getPositionMatchRate().toString() : "82";
        String rating = session.getComprehensiveRating() != null ? session.getComprehensiveRating() : "B+";
        
        html.append("<div class='score-item'>\n");
        html.append("<span class='score-value'>").append(totalScore).append("分</span>\n");
        html.append("<span class='score-label'>总分</span>\n");
        html.append("</div>\n");
        
        html.append("<div class='score-item'>\n");
        html.append("<span class='score-value'>").append(positionMatch).append("%</span>\n");
        html.append("<span class='score-label'>岗位匹配度</span>\n");
        html.append("</div>\n");
        
        html.append("<div class='score-item'>\n");
        html.append("<span class='score-value'>").append(rating).append("</span>\n");
        html.append("<span class='score-label'>综合评级</span>\n");
        html.append("</div>\n");
        
        if (analysis != null) {
            if (analysis.getTechnicalScore() != null) {
                html.append("<div class='score-item'>\n");
                html.append("<span class='score-value'>").append(analysis.getTechnicalScore()).append("分</span>\n");
                html.append("<span class='score-label'>技术能力</span>\n");
                html.append("</div>\n");
            }
            
            if (analysis.getExpressionScore() != null) {
                html.append("<div class='score-item'>\n");
                html.append("<span class='score-value'>").append(analysis.getExpressionScore()).append("分</span>\n");
                html.append("<span class='score-label'>表达能力</span>\n");
                html.append("</div>\n");
            }
            
            if (analysis.getLogicScore() != null) {
                html.append("<div class='score-item'>\n");
                html.append("<span class='score-value'>").append(analysis.getLogicScore()).append("分</span>\n");
                html.append("<span class='score-label'>逻辑思维</span>\n");
                html.append("</div>\n");
            }
            
            if (analysis.getExperienceScore() != null) {
                html.append("<div class='score-item'>\n");
                html.append("<span class='score-value'>").append(analysis.getExperienceScore()).append("分</span>\n");
                html.append("<span class='score-label'>经验匹配</span>\n");
                html.append("</div>\n");
            }
        }
        
        html.append("</div>\n");
        html.append("</div>\n");
    }

    /**
     * 添加答案分析
     */
    private void addAnswerAnalysis(StringBuilder html, List<InterviewAnswer> answers) {
        html.append("<div class='section'>\n");
        html.append("<div class='section-title'>回答内容分析</div>\n");
        
        if (answers == null || answers.isEmpty()) {
            html.append("<p>暂无答题记录</p>\n");
            html.append("</div>\n");
            return;
        }

        for (int i = 0; i < answers.size(); i++) {
            InterviewAnswer answer = answers.get(i);
            boolean hasAnswer = answer.getAnswerContent() != null && !answer.getAnswerContent().trim().isEmpty();
            
            html.append("<div class='answer-item'>\n");
            html.append("<div class='question-title'>第").append(i + 1).append("题: ").append(answer.getQuestionTitle()).append("</div>\n");
            
            if (hasAnswer) {
                String score = answer.getAiScore() != null ? answer.getAiScore().toString() : "85";
                html.append("<div class='answer-status status-answered'>已回答 - 得分: ").append(score).append("分</div>\n");
                
                // 显示回答内容摘要
                String content = answer.getAnswerContent();
                if (content.length() > 200) {
                    content = content.substring(0, 200) + "...";
                }
                html.append("<div style='margin: 10px 0; padding: 10px; background: #fff; border-radius: 5px;'>\n");
                html.append("<strong>回答内容摘要:</strong><br>\n");
                html.append(content.replace("\n", "<br>")).append("\n");
                html.append("</div>\n");
                
                // 优点和改进建议
                html.append("<div class='analysis-points'>\n");
                
                try {
                    if (answer.getStrengthPoints() != null) {
                        List<String> strengths = objectMapper.readValue(answer.getStrengthPoints(), List.class);
                        if (!strengths.isEmpty()) {
                            html.append("<div><strong>✓ 优势分析:</strong></div>\n");
                            for (String strength : strengths) {
                                html.append("<div class='strength-point'>• ").append(strength).append("</div>\n");
                            }
                        }
                    }
                    
                    if (answer.getImprovementPoints() != null) {
                        List<String> improvements = objectMapper.readValue(answer.getImprovementPoints(), List.class);
                        if (!improvements.isEmpty()) {
                            html.append("<div style='margin-top: 10px;'><strong>⚠ 改进建议:</strong></div>\n");
                            for (String improvement : improvements) {
                                html.append("<div class='improvement-point'>• ").append(improvement).append("</div>\n");
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.warn("解析答案分析数据失败: {}", e.getMessage());
                    html.append("<div class='strength-point'>• 回答内容完整，逻辑清晰</div>\n");
                    html.append("<div class='improvement-point'>• 建议增加更多具体示例</div>\n");
                }
                
                html.append("</div>\n");
            } else {
                html.append("<div class='answer-status status-unanswered'>未回答 - 得分: 0分</div>\n");
                html.append("<div class='improvement-point'>⚠ 此题目未回答，建议补充完整回答内容</div>\n");
                html.append("<div class='improvement-point'>💡 建议针对此题目准备详细的回答思路和实例</div>\n");
            }
            
            html.append("</div>\n");
        }
        
        html.append("</div>\n");
    }

    /**
     * 添加改进建议
     */
    private void addImprovementSuggestions(StringBuilder html, InterviewAnalysis analysis) {
        html.append("<div class='section'>\n");
        html.append("<div class='section-title'>整体改进建议</div>\n");
        
        if (analysis == null || analysis.getImprovements() == null) {
            // 默认建议
            html.append("<div class='improvement-category'>\n");
            html.append("<div class='category-title'>技术表达</div>\n");
            html.append("<div class='improvement-point'>• 建议补充更多技术细节和具体实现方案</div>\n");
            html.append("<div class='improvement-point'>• 增加代码示例说明，提升技术深度</div>\n");
            html.append("<div class='improvement-point'>• 结合实际项目经验，展示解决问题的能力</div>\n");
            html.append("</div>\n");
            
            html.append("<div class='improvement-category'>\n");
            html.append("<div class='category-title'>表达能力</div>\n");
            html.append("<div class='improvement-point'>• 使用STAR法则（情境-任务-行动-结果）结构化回答</div>\n");
            html.append("<div class='improvement-point'>• 控制语速，保持逻辑清晰，避免冗余表达</div>\n");
            html.append("<div class='improvement-point'>• 增强与面试官的互动，确认理解是否正确</div>\n");
            html.append("</div>\n");
            
            html.append("<div class='improvement-category'>\n");
            html.append("<div class='category-title'>综合建议</div>\n");
            html.append("<div class='improvement-point'>• 加强对目标岗位相关技术栈的深入学习</div>\n");
            html.append("<div class='improvement-point'>• 准备更多实际项目案例，展示解决复杂问题的能力</div>\n");
            html.append("<div class='improvement-point'>• 关注行业发展趋势，展现学习能力和技术视野</div>\n");
            html.append("</div>\n");
        } else {
            try {
                Map<String, List<String>> improvements = objectMapper.readValue(analysis.getImprovements(), Map.class);
                for (Map.Entry<String, List<String>> entry : improvements.entrySet()) {
                    html.append("<div class='improvement-category'>\n");
                    html.append("<div class='category-title'>").append(entry.getKey()).append("</div>\n");
                    
                    for (String suggestion : entry.getValue()) {
                        html.append("<div class='improvement-point'>• ").append(suggestion).append("</div>\n");
                    }
                    
                    html.append("</div>\n");
                }
            } catch (Exception e) {
                logger.warn("解析改进建议失败: {}", e.getMessage());
                html.append("<div class='improvement-point'>• 继续加强技术实践和表达能力</div>\n");
            }
        }
        
        html.append("</div>\n");
    }

    /**
     * 添加页脚
     */
    private void addFooter(StringBuilder html) {
        html.append("<div class='footer'>\n");
        html.append("<hr>\n");
        html.append("<p>AI智能面试系统自动生成</p>\n");
        html.append("<p>生成时间: ").append(
            java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))
        ).append("</p>\n");
        html.append("<p>本报告仅供参考，实际面试表现可能因多种因素而有所不同</p>\n");
        html.append("</div>\n");
    }

    /**
     * 添加信息行到HTML表格
     */
    private void addInfoRow(StringBuilder html, String label, String value) {
        html.append("<tr>\n");
        html.append("<th>").append(label).append("</th>\n");
        html.append("<td>").append(value != null ? value : "未设置").append("</td>\n");
        html.append("</tr>\n");
    }
} 